//
//  SharedViewController.swift
//  SwiftCode
//
//  Created by yuhus on 2023/9/22.
//

import Foundation
import UIKit
import Social
import RxSwift
import AVFoundation

extension ShareViewController {
  enum SharedType {
    case video(URL)
  }
}

final class ShareViewController: UIViewController {
  private let sharedType: SharedType
  
  private let containerSize = CGSize(width: 313, height: 347)
  private let imageSize = CGSize(width: 281.0, height: 130.0)
  private lazy var player = AVPlayer()
  
  private let bag = DisposeBag()
  
  deinit {
    Timber.d(#function)
  }
  
  init(with shareType: SharedType) {
    self.sharedType = shareType
    super.init(nibName: nil, bundle: nil)
    
    modalPresentationStyle = .overCurrentContext
    modalTransitionStyle = .crossDissolve
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  override var shouldAutorotate: Bool { false }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .black.withAlphaComponent(0.5)
    initView()
    initData()
  }
  
  private func initView() {
    view.addSubview(container)
    [titleLabel, closeButton, coverImageView, stackView, shareButton].forEach { subview in
      container.addSubview(subview)
    }
    
    if case .video = sharedType {
      [playerView, playButton].forEach { container.addSubview($0) }
      playerView.snp.makeConstraints { $0.edges.equalTo(coverImageView) }
      playButton.snp.makeConstraints { $0.center.equalTo(coverImageView) }
    }
    
    container.snp.makeConstraints { make in
      make.size.equalTo(containerSize)
      make.center.equalToSuperview()
    }
    titleLabel.snp.makeConstraints { make in
      make.top.equalTo(15)
      make.centerX.equalToSuperview()
    }
    closeButton.snp.makeConstraints { make in
      make.top.trailing.equalToSuperview().inset(12)
    }
    coverImageView.snp.makeConstraints { make in
      make.size.equalTo(imageSize)
      make.top.equalTo(45)
      make.centerX.equalToSuperview()
    }
    stackView.snp.makeConstraints { make in
      make.top.equalTo(coverImageView.snp.bottom).offset(34)
      make.centerX.equalToSuperview()
    }
    shareButton.snp.makeConstraints { make in
      make.leading.equalTo(16)
      make.bottom.equalTo(-12)
    }
  }
  
  @objc func closeButtonTapped(_ sender: UIButton) {
    dismiss(animated: true)
  }
  
  @objc func playButtonTapped(_ sender: UIButton) {
    player.seek(to: .zero)
    player.play()
    playButton.isHidden = true
  }
  
  @objc func playFinish() {
    playButton.isHidden = false
  }
  
  @objc func sharedButtonTapped(_ sender: UIButton) {
    Timber.d(sender.tag)
  }
  
  private func initData() {
    guard case let .video(url) = sharedType else { return }
    // Create an asset instance to represent the media file.
    let asset = AVAsset(url: url)
    loadPropertyValues(forAsset: asset)
  }
  
  private func loadPropertyValues(forAsset asset: AVAsset) {
    // 视频大小
    if let track = asset.tracks(withMediaType: .video).first {
      let width = track.naturalSize.width
      let height = track.naturalSize.height
      
      coverImageView.snp.updateConstraints { make in
        let w = width * imageSize.height / height
        make.size.equalTo(CGSize(width: w, height: imageSize.height))
      }
    }
    
    // 资源可播放
    let assetKeysRequiredToPlay = ["playable", "hasProtectedContent"]
    asset.loadValuesAsynchronously(forKeys: assetKeysRequiredToPlay) {
      DispatchQueue.main.async {
        if asset.isPlayable {
          self.playButton.isHidden = false
          self.playerView.player = self.player
          self.player.replaceCurrentItem(with: AVPlayerItem(asset: asset))
        }
      }
    }
    
    NotificationCenter.default.addObserver(self, selector: #selector(playFinish), name: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem)
  }
  
  private func setupTimeObserver() {
    let interval = CMTime(value: 1, timescale: 2)
    player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
      let timeElapsed = Float(time.seconds)
      Timber.d(timeElapsed)
    }
  }
  
  private lazy var container: UIView = {
    let view = UIView()
    view.backgroundColor = .white
    view.layer.cornerRadius = 20
    return view
  }()
  
  private lazy var titleLabel: UILabel = {
    let label = UILabel()
    label.textColor = .black
    label.font = .systemFont(ofSize: 16, weight: .black)
    label.text = "Recording"
    return label
  }()
  
  private lazy var closeButton: UIButton = {
    let button = UIButton()
    button.setImage(UIImage.close, for: .normal)
    button.addTarget(self, action: #selector(closeButtonTapped(_:)), for: .touchUpInside)
    return button
  }()
  
  private lazy var coverImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFit
    imageView.layer.cornerRadius = 10
    imageView.layer.masksToBounds = true
    return imageView
  }()
  
  private lazy var playerView: PlayerView = {
    let view = PlayerView()
    view.layer.cornerRadius = 10
    view.layer.masksToBounds = true
    view.layer.borderWidth = 0.5
    view.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
    return view
  }()
  
  private lazy var playButton: UIButton = {
    let button = UIButton()
    let image = UIImage(systemName: "play.circle.fill")?
      .withTintColor(UIColor.black, renderingMode: .alwaysOriginal)
      .withConfiguration(UIImage.SymbolConfiguration(pointSize: 28))
    button.setImage(image, for: .normal)
    button.isHidden = true
    button.addTarget(self, action: #selector(playButtonTapped(_:)), for: .touchUpInside)
    return button
  }()
  
  private lazy var stackView: UIStackView = {
    var buttons: [UIButton] = []
    for i in 1...5 {
      let button = UIButton()
      let image = UIImage(systemName: "die.face.\(i).fill")?
        .withTintColor(UIColor.gray, renderingMode: .alwaysOriginal)
        .withConfiguration(UIImage.SymbolConfiguration(pointSize: 28))
      button.setImage(image, for: .normal)
      button.tag = i
      button.addTarget(self, action: #selector(sharedButtonTapped(_:)), for: .touchUpInside)
      buttons.append(button)
    }
    let stack = UIStackView(arrangedSubviews: buttons)
    stack.axis = .horizontal
    stack.alignment = .center
    stack.spacing = 15
    return stack
  }()
  
  private lazy var shareButton: UIButton = {
    let button = UIButton()
    button.setTitle("分享", for: .normal)
    button.setTitleColor(.black, for: .normal)
    return button
  }()
}

fileprivate extension UIImage {
  static let close = UIImage(systemName: "xmark.circle.fill")?
    .withTintColor(UIColor.gray, renderingMode: .alwaysOriginal)
    .withConfiguration(UIImage.SymbolConfiguration(pointSize: 28))
}
